package com.bjsdzk.collector.config;

import com.bjsdzk.collector.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Order(1)
public class RedisClear implements CommandLineRunner {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static Logger logger = LoggerFactory.getLogger(RedisClear.class);

    private static final String CACHE_KEY_PREFIX_CLEAR= "cache_*" ;

    @Override
    public void run(String... args) {
        Cursor<String> scan = RedisUtil.scan(redisTemplate, CACHE_KEY_PREFIX_CLEAR, 100);
        Set<String> keys = new HashSet<>(32);
        while (scan.hasNext()) {
            keys.add(scan.next());
        }
        try {
            if (!scan.isClosed()) {
                scan.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        keys = redisTemplate.keys(CACHE_KEY_PREFIX_CLEAR);
        if (!keys.isEmpty()) {
            Long aLong = redisTemplate.delete(keys);
            logger.info("start project clear redis count:{}", aLong);
        }
    }


}
